<?php
require_once dirname(dirname(dirname(dirname(__FILE__)))) . '/init.php';

/**
 *向(财务系统)fin同步仓库部门信息
 *@author shipanpan
 */
class SynWarehouseDepController extends Controller_CronJob {
	private $_domain;
	private $_authToken;
	private $_authSn;

	public function __construct() {
		$this->_domain = Helper_Config::get('url', 'fin', 'url');
		$this->_authToken = Helper_Config::get('auth', 'fin', 'token');
		$this->_authSn = Helper_Config::get('auth', 'fin', 'sn');

		parent::__construct();
	}

	public function run() {
		$url = $this->_domain . 'inter/department/get?' . 'token=' . $this->_authToken . '&sn=' . $this->_authSn;
		$perPage = 1000;
		try {
			$response = Controller_Interface::post($url, ['page' => 1, 'per_page' => $perPage]);
			$warehouseDep = json_decode($response, true);
		} catch (Exception $e) {
			$errorMsg = "向财务系统同步仓库平台数据发生错误:" . $e->getMessage();
			$this->log->record($errorMsg, Log::WARN);
			die($errorMsg);
		}

		if (!$warehouseDep) {
			$errorMsg = "向财务系统同步仓库平台数据发生错误:" . json_last_error_msg();
			$this->log->record($errorMsg, Log::WARN);
			die($errorMsg);
		}

		if (!isset($warehouseDep['total'], $warehouseDep['page'], $warehouseDep['per_page'])) {
			$errorMsg = "财务系统返回的仓库平台数据异常";
			$this->log->record($errorMsg, Log::WARN);
			die($errorMsg);
		}
		if (!$warehouseDep['total'] || !$warehouseDep['page'] || !$warehouseDep['per_page']) {
			$errorMsg = "财务系统返回的仓库平台数据格式异常";
			$this->log->record($errorMsg, Log::WARN);
			die($errorMsg);
		}

		foreach ($warehouseDep['list'] as $_oneWarehouseDep) {
			$weNeedWarehouseDepData = [];
			$weNeedWarehouseDepData['department_sn'] = $_oneWarehouseDep['sn'];
			$weNeedWarehouseDepData['department_name'] = $_oneWarehouseDep['name'];
			$weNeedWarehouseDepData['status'] = $_oneWarehouseDep['status'] == 1 ? 1 : 0;
			Model_Base::insertOrUpdate($this->writeDb, 'c_warehouse_dept', $weNeedWarehouseDepData);
		}
		$this->log->record('同步仓库部门成功！');
		die('同步仓库部门成功！');
	}

}

$synWarehouseDep = new SynWarehouseDepController();
$synWarehouseDep->run();